package com.sdp.wx.handleImpl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.wx.controller.WxRepairCodeController;
import com.sdp.wx.controller.WxSysConfigController;
import com.sdp.wx.db.wx_warehouse_info.entity.WxWarehouseInfo;
import com.sdp.wx.db.wx_warehouse_info.service.IWxWarehouseInfoService;
import com.sdp.wx.db.wx_warehouse_right.service.IWxWarehouseRightService;
import com.sdp.wx.db.wx_wz_input.entity.WxWzInput;
import com.sdp.wx.db.wx_wz_input.service.IWxWzInputService;
import com.sdp.wx.db.wx_wz_input_detail.entity.WxWzInputDetail;
import com.sdp.wx.db.wx_wz_input_detail.service.IWxWzInputDetailService;
import com.sdp.wx.db.wx_wz_inventory.entity.WxWzInventory;
import com.sdp.wx.db.wx_wz_inventory.service.IWxWzInventoryService;
import com.sdp.wx.db.wx_wz_inventory_detail.entity.WxWzInventoryDetail;
import com.sdp.wx.db.wx_wz_inventory_detail.service.IWxWzInventoryDetailService;
import com.sdp.wx.db.wx_wz_now_num.service.IWxWzNowNumService;
import com.sdp.wx.handle.WzInOutPutHandle;
import com.sdp.wx.utils.CurrentLoginEmp;
import com.sdp.wx.utils.WxConstants;

@Component
public class WzInventoryInputHandlerImpl extends WzInOutPutHandle{
	
	@Autowired
	private CurrentLoginEmp currentLoginEmp;
	
	@Autowired
	private IWxWarehouseInfoService iWxWarehouseInfoService;
	
	@Autowired
	private IWxWarehouseRightService iWxWarehouseRightService;
	
	@Autowired
	private IWxWzNowNumService iWxWzNowNumService;
	
	@Autowired
	private IWxWzInputDetailService iWxWzInputDetailService;
	
	@Autowired
	private IWxWzInputService iWxWzInputService;
	
	@Autowired
	private WxRepairCodeController wxRepairCodeController;
	
	@Autowired
	private IWxWzInventoryService iWxWzInventoryService;
	
	@Autowired
	private IWxWzInventoryDetailService	iWxWzInventoryDetailService;
	
	@Autowired
	private WxSysConfigController wxSysConfigController;

	@Override
	public BusinessContext execute(BusinessContext businessContext) {
		return ApplicationContextUtils.getBean(WzInventoryInputHandlerImpl.class).inventoryInput(businessContext);
	}
	
	@Transactional(rollbackFor=Exception.class)
	public BusinessContext inventoryInput(BusinessContext businessContext) {
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if(StringUtils.isEmpty(emp)) {
			businessContext.setMessage("请先登录系统");
			businessContext.setSuccess(false);
			return businessContext;
		}
		
		List<WxWzInputDetail> wzList = businessContext.get(WxWzInputDetail.class);
		WxWzInput input = businessContext.get(WxWzInput.class);
		if(input==null || wzList==null || wzList.size()==0) {
			businessContext.setSuccess(false);
			businessContext.setMessage("入库器材不存在，不能出库");
			return businessContext;
		}
		
		if(input.getInventoryId()==null || StringUtils.isEmpty(input.getInventoryName())) {
			businessContext.setSuccess(false);
			businessContext.setMessage("请先选择盘存单！");
			return businessContext;
		}
		
		WxWzInventory wzInventory = iWxWzInventoryService.getById(input.getInventoryId());
		
		if(wzInventory==null) {
			businessContext.setSuccess(false);
			businessContext.setMessage("选择的盘存单信息不存在，请先进行核对！");
			return businessContext;
		}
		if(WxConstants.是.getCode().equals(wzInventory.getHandleState())) {
			businessContext.setSuccess(false);
			businessContext.setMessage("选择的盘存单已完成调差，不能再进行处理！");
			return businessContext;
		}
		
		//判断仓库是否锁定
		WxWarehouseInfo warehouseInfo = iWxWarehouseInfoService.queryWxWarehouseInfoByCode(input.getWarehouseCode());
		if(warehouseInfo==null || WxConstants.是.getCode().equals(warehouseInfo.getIsLock())) {
			businessContext.setMessage("仓库目前处于盘存状态，无法进行出库");
			businessContext.setSuccess(false);
			return businessContext;
		}
		
		//判断当前操作人是否有报废出库的权限
		boolean haveRight = iWxWarehouseRightService.isHaveRight(emp.getString("empNo"), input.getWarehouseCode(),WxConstants.库管权限_盘盈入库.getCode());
		if(!haveRight) {
			businessContext.setMessage("您没有此仓库的盘盈入库权限");
			businessContext.setSuccess(false);
			return businessContext;
		}
		
		
		Map<String,BigDecimal> wzInputNumMap = new HashMap<>();

		for(WxWzInputDetail wz : wzList) {
			if(wzInputNumMap.containsKey(wz.getWzNo())) {
				wzInputNumMap.put(wz.getWzNo(), wz.getInputNum().add(wzInputNumMap.get(wz.getWzNo())));
			}else {
				wzInputNumMap.put(wz.getWzNo(), wz.getInputNum());
			}
		}
		
		//与盘存单进行比对，看数据是否合法
		boolean flag = false;
		List<WxWzInventoryDetail> inventoryDetailList = iWxWzInventoryDetailService.queryWzInventoryDetailByInventoryId(input.getInventoryId());
		for(WxWzInventoryDetail wz :inventoryDetailList) {
			if(wzInputNumMap.containsKey(wz.getWzNo())) {
				if(wzInputNumMap.get(wz.getWzNo()).compareTo(wz.getInventoryDif())>0) {
					flag = true;
				}
				wz.setInventoryDif(wz.getInventoryDif().subtract(wzInputNumMap.get(wz.getWzNo())));
			}

		}
		if(flag) {
			businessContext.setSuccess(false);
			businessContext.setMessage("入库数量不能大于误差数量，请先进行核对！");
			return businessContext;
		}
		
	
		String armRatio = wxSysConfigController.getSysConfigParamValByCode(WxConstants.参数配置_军价上浮比例.getCode());
		String saleRatio = wxSysConfigController.getSysConfigParamValByCode(WxConstants.参数配置_对外销售价上浮比例.getCode());
		List<String> wzNoList = new ArrayList<String>();
		BigDecimal inputAmount = BigDecimal.ZERO;
		LocalDateTime now = LocalDateTime.now();
		input.setOpName(emp.getString("empName"));
		input.setOpNo(emp.getString("empNo"));
		input.setCreateTime(now);
		input.setInputTime(now);
		input.setInputDate(LocalDate.now());
		input.setIsUse(WxConstants.是.getCode());
		input.setIsOutput(WxConstants.否.getCode());
		input.setInputCode(wxRepairCodeController.getCode(WxConstants.流水号前缀_器材入库单.getCode(), WxConstants.流水号类型_器材入库单.getCode()));
		input.setInputType(WxConstants.入库类型_盘盈入库.getCode());
		for(WxWzInputDetail wz : wzList) {
			wz.setKeyId(null);
			wz.setInputCode(input.getInputCode());
			wz.setNowNum(wz.getInputNum());
			wz.setCreateTime(now);
			wz.setArmyPrice(wz.getPurchasePrice().add(wz.getPurchasePrice().multiply(new BigDecimal(armRatio).divide(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_HALF_UP)));
			wz.setSalePrice(wz.getPurchasePrice().add(wz.getPurchasePrice().multiply(new BigDecimal(saleRatio).divide(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_HALF_UP)));
			wz.setUnqualifiedNum(BigDecimal.ZERO);
			wz.setArrivalNum(BigDecimal.ZERO);
			inputAmount = inputAmount.add(wz.getPurchasePrice().multiply(wz.getInputNum()).setScale(2, BigDecimal.ROUND_HALF_UP));
			wzNoList.add(wz.getWzNo());
		}
		input.setInputAmount(inputAmount);
		
		//入库操作
		iWxWzInputService.save(input);
		iWxWzInputDetailService.saveBatch(wzList);
			
		//更新库存
		iWxWzNowNumService.wzNowNumAdd(wzNoList, wzInputNumMap,input.getWarehouseCode());
		
		//更新盘存物资中的误差数量
		iWxWzInventoryDetailService.updateBatchById(inventoryDetailList);
		return businessContext;
	}

}
